﻿using System;
using System.Collections.Generic;
using BO.Infrastructure.Utils;
using ChannelVN.Cached;
using Utilities.Entities;

namespace BO.Solr
{
    public class SolrBO
    {
        static readonly string UniqueText = typeof(SolrBO).Namespace + typeof(SolrBO).Name;

        static string BuildCacheKey(string methodName, IEnumerable<object> listParams)
        {
            return PresentationUtils.GetCacheKey(methodName, listParams, UniqueText);
        }

        public static SearchResult SearchNewsByTag(string tagUrl, int pageIndex, int pageSize, int topExclusion = 0)
        {
            var cacheKey = BuildCacheKey("SearchNewsByTag", new object[] { tagUrl, pageIndex, pageSize, topExclusion });
            var result = CacheController.GetMemcachedInstanceForDataCached().Get<SearchResult>(CacheController.CacheGroupForDataCached, cacheKey);

            if (result == null)
            {
                result = SolrBO_NoCache.SearchNewsByTag(tagUrl, pageIndex, pageSize, topExclusion);

                if (result != null)
                {
                    CacheController.GetMemcachedInstanceForDataCached().Add(CacheController.CacheGroupForDataCached, cacheKey, result, DateTime.Now.AddMinutes(15));
                }
            }
            return result;
        }

        public static SearchResult SearchNewsByKeywords(string keywords, int pageIndex, int pageSize, bool exactlySearching = true)
        {
            var cacheKey = BuildCacheKey("SearchNewsByKeywords", new object[] { keywords, pageIndex, pageSize, exactlySearching });
            var result = CacheController.GetMemcachedInstanceForDataCached().Get<SearchResult>(CacheController.CacheGroupForDataCached, cacheKey);

            if (result == null)
            {
                result = SolrBO_NoCache.SearchNewsByKeywords(keywords, pageIndex, pageSize, exactlySearching);

                if (result != null)
                {
                    CacheController.GetMemcachedInstanceForDataCached().Add(CacheController.CacheGroupForDataCached, cacheKey, result, DateTime.Now.AddMinutes(3));
                }
            }
            return result;
        }
    }
}
